package cn.xlbweb.sso.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author: bobi
 * @date: 2019-03-24 21:40
 * @description:
 */
@Slf4j
public class TimeInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute("remoteAddr", request.getRemoteAddr());
        request.setAttribute("startTime", System.currentTimeMillis());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String remoteAddr = (String) request.getAttribute("remoteAddr");
        Long startTime = (Long) request.getAttribute("startTime");
        Long durationTime = System.currentTimeMillis() - startTime;
        log.info("IP:{} 请求地址:{} 共花费:{}ms", remoteAddr, request.getRequestURI(), durationTime);
    }
}
